package com.ssy.mall.filter;

import com.ssy.mall.common.Constant;
import com.ssy.mall.model.pojo.User;
import com.ssy.mall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: 苏少有的idea
 * @date:   2021/12/17
 * @description  管理员校验过滤器
 */
public class AdminFilter implements Filter {
    @Autowired
    UserService userService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute(Constant.SSY_MALL_USER);
        if (currentUser == null) {
            //因为该方法的返回值是void，此时不能通过return返回，但是又想拿到异常枚举，故用HttpServletResponseWrapper
            //return ApiRestResponse.error(SsyMallExceptionEnum.NEED_LOGIN);
            PrintWriter out =  new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10007,\n" +
                    "    \"msg\": \"NEED_LOGIN\",\n" +
                    "    \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
            return;//指的是方法执行到这就结束了
        }
        //校验是否为管理员
        boolean adminRole = userService.checkAdminRole(currentUser);
        //是管理员执行操作
        if (adminRole) {
            //如果是管理员会进行放行
           filterChain.doFilter(servletRequest,servletResponse);

        } else {
            PrintWriter out =  new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10009,\n" +
                    "    \"msg\": \"NEED_ADMIN\",\n" +
                    "    \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
        }

    }

    @Override
    public void destroy() {

    }
}
